/*
package com.imay.live.activity.camera;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Point;
import android.graphics.Rect;
import android.hardware.Camera;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.imay.capturefilter.MagicEngine;
import com.imay.capturefilter.R;
import com.imay.capturefilter.adapter.FilterAdapter;
import com.imay.capturefilter.camera.CameraEngine;
import com.imay.capturefilter.filter.helper.MagicFilterType;
import com.imay.capturefilter.helper.SavePictureTask;
import com.imay.capturefilter.utils.ICCons;
import com.imay.capturefilter.utils.ICUtils;
import com.imay.capturefilter.utils.MagicFilterTools;
import com.imay.capturefilter.utils.MagicParams;
import com.imay.capturefilter.utils.PermissionUtil;
import com.imay.capturefilter.widget.ICAutoAdjustRecylerView;
import com.imay.capturefilter.widget.ICGridView;
import com.imay.capturefilter.widget.IMMagicCameraView;
import com.imay.capturefilter.widget.MagicCameraView;
import com.imay.live.analytics.MobclickAgent;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.imay.capturefilter.R.id.glsurfaceview_camera;

public class CameraActivity extends Activity implements View.OnClickListener, IMMagicCameraView.MagicListener {

    private static final String TAG = "CameraActivity";
    private IMMagicCameraView mMagicCameraView;

    private MagicEngine mMagicEngine;
    private ICAutoAdjustRecylerView mRecyclerView;
    private FilterAdapter mAdapter;

    //闪关灯按钮            // 网格按钮  //焦点图片
    private ImageView mIvFlash, mIvGrid, mIvFocus;
    private ICGridView mGridView;

    private int mFlashMode = 0; //0关，1自动，2开, 3禁用：前置摄像头，

    private int CAMERA_TYPE = 0;

    public static void startActivity(Activity activity, int requestCode) {
        Intent intent = new Intent(activity, CameraActivity.class);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.capturefilter_activity_camera);
        initView(savedInstanceState);
    }

    protected void initView(Bundle savedInstanceState) {
        ICUtils.deleteFile(this);

        Point screenSize = new Point();
        getWindowManager().getDefaultDisplay().getSize(screenSize);

        // 获取屏幕宽度
        ICCons.screenW = screenSize.x;
        ICCons.screenH = screenSize.y;

        // 开启是否前置摄像
        CAMERA_TYPE = getIntent().getIntExtra(ICCons.KEY_CAMERA_TYPE, 0);
        if (CAMERA_TYPE == ICCons.CAMERA_IS_ID_CARD) {
            MagicParams.IS_ID_CARD_CAMERA = true;
        } else {
            MagicParams.IS_ID_CARD_CAMERA = false;
        }
        MagicParams.OPEN_CAMERA_ID = CAMERA_TYPE;

        */
/**
         * 权限控制
         *//*

        List<String> permissionList = new ArrayList<>();
        if (!PermissionUtil.selfPermissionGranted(this, Manifest.permission.CAMERA)) {
            permissionList.add(Manifest.permission.CAMERA);
        }
        if (!PermissionUtil.selfPermissionGranted(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (!PermissionUtil.selfPermissionGranted(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            permissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        if (!permissionList.isEmpty()) {
            String[] permissions = new String[permissionList.size()];
            permissionList.toArray(permissions);
            ActivityCompat.requestPermissions(this, permissions,
                    1);
        }

        initView();

        */
/**
         * 设置闪光灯图片
         *//*

        if (CameraEngine.getCameraBackStatus()) {
            mIvFlash.setImageResource(R.mipmap.btn_03_camera_flash_clos);
        } else {
            mIvFlash.setImageResource(R.mipmap.btn_03_camera_flash_clos_disable);
        }
        MobclickAgent.onEvent(CameraActivity.this, "photo_open");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            for (int i = 0; i < permissions.length; i++) {
                if (permissions[i].equals(Manifest.permission.CAMERA)) {
                    int status = grantResults[i];
                    if (status == 0) {
                        */
/**
                         * 当相机因第一次无法获取权限异常open时返回false信息，进行activty的重启操作
                         *//*

                        if (!ICCons.cameraOrNull) {
                            recreate();
                        }
                    } else if (status == -1) {
                        Toast.makeText(this, getString(R.string.message_denied), Toast.LENGTH_SHORT).show();
                        finish();
                    }
                    break;
                }
            }
        }
    }

    private void initView() {
        // 获取摄像机
        MagicEngine.Builder builder = new MagicEngine.Builder();
        mMagicCameraView = (IMMagicCameraView) findViewById(glsurfaceview_camera);
        mMagicEngine = builder.build(mMagicCameraView);

        // 初始化其他控件
        findViewById(R.id.iv_close).setOnClickListener(this); //关闭
        findViewById(R.id.iv_btn_capture).setOnClickListener(this); //拍照
        findViewById(R.id.iv_btn_sys_photo).setOnClickListener(this);   //系统相册
        findViewById(R.id.iv_switch_camera).setOnClickListener(this);   //切换相机
        mMagicCameraView.setListener(this);

        mIvFlash = (ImageView) findViewById(R.id.iv_flash); //闪光灯
        mIvFlash.setOnClickListener(this);
        mIvGrid = (ImageView) findViewById(R.id.iv_grid);   //网格线
        mIvGrid.setOnClickListener(this);

        mGridView = (ICGridView) findViewById(R.id.imay_capture_gridview);
        mIvFocus = (ImageView) findViewById(R.id.iv_focus);

        mRecyclerView = (ICAutoAdjustRecylerView) findViewById(R.id.recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayout.HORIZONTAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setPxPerMillsec(1.0f);

        MagicFilterTools filterTools = MagicFilterTools.getInstance(CameraActivity.this);
        mAdapter = new FilterAdapter(this, MagicFilterTools.types, filterTools.getFilterNames(CameraActivity.this));
        mAdapter.setOnFilterChangeListener(onFilterChangeListener);
        mRecyclerView.setAdapter(mAdapter);

        RelativeLayout rl_content = (RelativeLayout) findViewById(R.id.rl_content);
        rl_content.setLayoutParams(new LinearLayout.LayoutParams(ICCons.screenW, ICCons.screenW));
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_close) {  //关闭拍照
            closeActivity();
            return;
        } else if (id == R.id.iv_btn_sys_photo) {    //系统相册
            try {
                Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
                photoPickerIntent.setType("image*/
/*");
                startActivityForResult(photoPickerIntent, ICCons.REQUEST_PICK_IMAGE);
                MobclickAgent.onEvent(CameraActivity.this, "phote_click_album");
            } catch (Exception e) {

            }
            return;
        } else if (id == R.id.iv_btn_capture) {  //拍照
            // 注意必须每次都要设置闪光灯
            //Log.i(TAG,mFlashMode+"");
            mMagicEngine.setFlashMode(mFlashMode);
            Camera camera = CameraEngine.getCamera();
            if (camera != null) {
                if (camera.getParameters().getFocusMode().equals(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
                    takePhoto();
                } else {
                    if (mMagicCameraView.getState() == IMMagicCameraView.State.NONE) { // 触摸对焦后牌照
                        takePhoto();
                    } else { // 首次没有触摸
                        CameraEngine.getCamera().autoFocus(new Camera.AutoFocusCallback() {
                            @Override
                            public void onAutoFocus(final boolean success, final Camera camera) {
                                takePhoto();
                            }
                        });
                    }
                }
            }
            MobclickAgent.onEvent(CameraActivity.this, "photo_click_taken");
            return;
        } else if (id == R.id.iv_switch_camera) {   //切换相机
            mMagicCameraView.switchCamera();
            setViewFlasMode();  //更改下闪光灯模式
            return;
        } else if (id == R.id.iv_flash) {  //闪光灯
            //切换效果，逐次改变，从关闭，自动，打开
            setFlashMode();
            return;
        } else if (id == R.id.iv_grid) {   //网格线
            showOrHidGridView();
            return;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (resultCode == RESULT_OK) {
                if (requestCode == ICCons.REQUEST_PICK_IMAGE) {    //系统相册返回
                    if (data != null) {
                        Message msg = new Message();
                        msg.what = 0;
                        msg.obj = data.getData().toString();
                        mHandler.sendMessage(msg);
                    }
                } else if (requestCode == ICCons.REQUEST_CLIP_IMAGE) {  //图片裁剪返回
                    if (data != null) {
                        Bundle b = data.getExtras();
                        String path = b.getString(ICCons.KEY_FILE_PATH);
                        Intent intent = new Intent();
                        intent.putExtra(ICCons.KEY_FILE_PATH, path);
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                }
            }
        } catch (Exception e) {

        }
    }

    private FilterAdapter.FilterChangeListener onFilterChangeListener = new FilterAdapter.FilterChangeListener() {
        @Override
        public void onFilterChanged(MagicFilterType filterType, int position) {
            mMagicEngine.setFilter(filterType);
            mRecyclerView.checkAutoAdjust(position);
        }
    };

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                Intent intent = new Intent(CameraActivity.this, ClipActivity.class);
                intent.putExtra(ICCons.KEY_FILE_URI, (String) msg.obj);
                startActivityForResult(intent, ICCons.REQUEST_CLIP_IMAGE);
            } else if (msg.what == 1) {
                Toast.makeText(CameraActivity.this, getString(R.string.message_denied), Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    };

    private void takePhoto() {
        final Dialog dialog = ICUtils.createDialog(this, getString(R.string.IC_img_msg_create));
        dialog.show();
        File imageFile = ICUtils.getOutputMediaFile(CameraActivity.this);
        if (imageFile != null) {
            mMagicEngine.savePicture(imageFile, new SavePictureTask.OnPictureSaveListener() {
                @Override
                public void onSaved(final String result) {
                    // 返回图片路径
                    dialog.dismiss();
                    MediaScannerConnection.scanFile(CameraActivity.this,
                            new String[]{result}, null,
                            new MediaScannerConnection.OnScanCompletedListener() {
                                @Override
                                public void onScanCompleted(final String path, final Uri uri) {
                                    // 返回图片路径
                                    Intent intent = new Intent(CameraActivity.this, ClipActivity.class);
                                    intent.putExtra(ICCons.KEY_FILE_PATH, result);
                                    startActivityForResult(intent, ICCons.REQUEST_CLIP_IMAGE);
                                }
                            });
                }
            });
        } else {
            dialog.dismiss();
            Toast.makeText(CameraActivity.this, "保存图片失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void showOrHidGridView() {
        if (mGridView.getVisibility() == View.VISIBLE) {
            mGridView.setVisibility(View.GONE);
        } else {
            RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams) mGridView.getLayoutParams();
            if (mMagicCameraView.getHeight() < ICCons.screenW) {
                p.setMargins(0, 0, 0, 0);
            } else {
                p.setMargins(0, (mMagicCameraView.getHeight() - ICCons.screenW) / 2, 0, 0);
            }
            mGridView.setLayoutParams(p);
            mGridView.setVisibility(View.VISIBLE);
        }
    }

    private void setFlashMode() {
        if (mFlashMode > 1) {
            mFlashMode = 0;
        } else {
            mFlashMode = mFlashMode + 1;
        }
        setViewFlasMode();
    }

    private void setViewFlasMode() {
        if (!CameraEngine.getCameraBackStatus()) {//前置摄像头，不可用
            mMagicEngine.setFlashMode(3);
            mIvFlash.setEnabled(false);
            mIvFlash.setImageResource(R.mipmap.btn_03_camera_flash_clos_disable);
        } else {
            mMagicEngine.setFlashMode(mFlashMode);
            mIvFlash.setEnabled(true);
            mIvGrid.setSelected(false);
            mIvGrid.setEnabled(true);
            //mGridView.setVisibility(View.GONE);
            if (mFlashMode == 1) {
                mIvFlash.setImageResource(R.mipmap.btn_03_camera_flash_auto);
            } else if (mFlashMode == 2) {
                mIvFlash.setImageResource(R.mipmap.btn_03_camera_flash_default);
            } else {
                mIvFlash.setImageResource(R.mipmap.btn_03_camera_flash_clos);
            }
        }
    }

    private void closeActivity() {
        finish();
    }


    @Override
    protected void onDestroy() {
        mMagicEngine = null;
        mMagicCameraView = null;
        mRecyclerView = null;
        mAdapter = null;
        MagicParams.magicBaseView = null;
        MagicParams.IS_ID_CARD_CAMERA = false;
        MagicParams.OPEN_CAMERA_ID = 0;
        CameraEngine.onDestroy();
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        findViewById(R.id.iv_btn_capture).setEnabled(true);
        try {
            mMagicCameraView.resumeCamera();
        } catch (Exception e) {
            e.printStackTrace();
        }
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        try {
            mMagicCameraView.pauceCamera();
        } catch (Exception e) {
            e.printStackTrace();
        }
        MobclickAgent.onPause(this);
    }

    */
/**
     * 更新滤镜
     *
     * @param position
     *//*

    private void updateFilter(int position) {
        mMagicEngine.setFilter(MagicFilterTools.types[position]);
        mAdapter.setSelected(position);
        mRecyclerView.checkAutoAdjust(position);
        mAdapter.notifyDataSetChanged();
    }

    private void updateFocusUI(int mFocusX, int mFocusY) {
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mIvFocus.getLayoutParams();
        params.setMargins(mFocusX - 50, mFocusY - 50, 0, 0);
        mIvFocus.setLayoutParams(params);
        mIvFocus.setVisibility(ImageView.VISIBLE);
        // 属性动画
        AnimatorSet set = new AnimatorSet();
        ObjectAnimator oaX = ObjectAnimator.ofFloat(mIvFocus, "scaleX", 1.0f, 1.1f);
        ObjectAnimator oaY = ObjectAnimator.ofFloat(mIvFocus, "scaleY", 1.0f, 1.1f);
        ObjectAnimator oaX2 = ObjectAnimator.ofFloat(mIvFocus, "scaleX", 1.1f, 0.9f);
        ObjectAnimator oaY2 = ObjectAnimator.ofFloat(mIvFocus, "scaleY", 1.1f, 0.9f);
        ObjectAnimator oaX3 = ObjectAnimator.ofFloat(mIvFocus, "scaleX", 0.9f, 1.0f);
        ObjectAnimator oaY3 = ObjectAnimator.ofFloat(mIvFocus, "scaleY", 0.9f, 1.0f);
        set.play(oaX).with(oaY);
        set.play(oaX).before(oaX2).before(oaY2);
        set.play(oaX2).before(oaX3).before(oaY3);
        set.setDuration(300);
        set.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {

            }

            @Override
            public void onAnimationEnd(Animator animator) {
                mIvFocus.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
        set.start();
    }

    @Override
    public void foucus(int focusX, int focusY) {
        updateFocusUI(focusX, focusY);
    }

    @Override
    public void flingLeft() {
        int pos = mAdapter.getSelected();
        if (pos < mAdapter.getItemCount() - 1) {
            pos = pos + 1;
            updateFilter(pos);
        }
    }

    @Override
    public void flingRight() {
        int pos = mAdapter.getSelected();
        if (pos > 0) {
            pos = pos - 1;
            updateFilter(pos);
        }
    }
}
*/
